package com.yxt.qmgf.tzfe.ctrl;

import com.yxt.qmgf.common.ImageSrc;
import com.yxt.qmgf.shop.ctrl.ShopController;
import com.yxt.qmgf.tzfe.view.cardMatrixPane;
import com.yxt.qmgf.userinfo.vo.UserInfoVO;
import de.felixroske.jfxsupport.FXMLController;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Insets;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.layout.BorderPane;
import javafx.stage.Modality;
import javafx.stage.Stage;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@FXMLController
public class tzfeInfoController implements gameMenuBar.Callbacks, cardMatrixPane.Callbacks {

    private UserInfoVO vo;
    private Stage stage;

    @FXML
    public Button backButton;

    private BorderPane borderPane;
    private gameMenuBar menuBar;
    private cardMatrixPane cardMatrixPane;

    Image icon = new Image(ImageSrc._2048_logo_path);

    public void setOff(UserInfoVO vo) {
        this.vo = vo;
    }

    @FXML
    public void startGame() {
        if (stage == null) {
            stage = new Stage(); // 如果没有 Stage，就新建一个
        }

        borderPane = new BorderPane();
        Scene scene = new Scene(borderPane, 1000, 600);

        // Top菜单栏
        menuBar = new gameMenuBar(this); // 传入 this 作为回调
        borderPane.setTop(menuBar);

        // Center 2048 卡片矩阵
        cardMatrixPane = new cardMatrixPane(this);
        cardMatrixPane.setPadding(new Insets(5, 5, 5, 5));
        borderPane.setCenter(cardMatrixPane);

        stage.setTitle("2048");
        stage.getIcons().add(icon);
        stage.setScene(scene);
        stage.show();

        initGame();
    }

    /** 初始化游戏逻辑 */
    private void initGame() {
        cardMatrixPane.requestFocus(); // 添加焦点
        cardMatrixPane.createKeyListener(vo); // 添加键盘监听
        menuBar.saveCurrentScore();
        afterScoreChange(); // 更新分数显示
    }

    @Override
    public void afterRestart() {
        cardMatrixPane.restartMatrix();
    }

    @Override
    public void afterResetGridSize(int cols, int rows) {
        cardMatrixPane = new cardMatrixPane(cols, rows, this);
        cardMatrixPane.setPadding(new Insets(5, 5, 5, 5));
        borderPane.setCenter(cardMatrixPane);
        initGame();
    }

    @Override
    public void afterScoreChange() {
        menuBar.getScoreMenu().setText("分数: " + cardMatrixPane.getScore());
    }

    @Override
    public void afterGetMoreScoreInfo() {
        int[] temp = cardMatrixPane.getMcQuantities();
        Alert alert = new Alert(AlertType.INFORMATION);
        Stage stage = (Stage) alert.getDialogPane().getScene().getWindow();
        stage.getIcons().add(icon);
        alert.setTitle("合并次数统计");
        alert.setContentText(
                "4的合并次数:      " + temp[0] + "\n" +
                        "8的合并次数:      " + temp[1] + "\n" +
                        "16的合并次数:     " + temp[2] + "\n" +
                        "32的合并次数:     " + temp[3] + "\n" +
                        "64的合并次数:     " + temp[4] + "\n" +
                        "128的合并次数:    " + temp[5] + "\n" +
                        "256的合并次数:    " + temp[6] + "\n" +
                        "512的合并次数:    " + temp[7] + "\n" +
                        "1024的合并次数:   " + temp[8] + "\n" +
                        "2048的合并次数:   " + temp[9] + "\n" +
                        "4096的合并次数:   " + temp[10] + "\n" +
                        "8192的合并次数:   " + temp[11] + "\n" +
                        "16384的合并次数:  " + temp[12] + "\n" +
                        "32768的合并次数:  " + temp[13] + "\n" +
                        "65536的合并次数:  " + temp[14] + "\n");
        alert.show();
    }

    @Override
    public long getCurrentScore() {
        return cardMatrixPane.getScore();
    }

    @FXML
    public void role() {
        Alert alert = new Alert(AlertType.INFORMATION);
        Stage stage = (Stage) alert.getDialogPane().getScene().getWindow();
        stage.getIcons().add(icon);
        alert.setTitle("2048游戏规则");
        alert.setContentText("操作方式:\n"+
                "向上滑动:方向键↑或键W\n"+
                "向下滑动:方向键↓或键S\n"+
                "向左滑动:方向键←或键A\n"+
                "向右滑动:方向键→或键D\n"+
                "\n游戏规则:\n"+
                "相同数字的卡片在靠拢、相撞时会合并\n"+
                "在操作中合并的卡片会以红色边框凸显\n尽可能获得更大的数字!");
        alert.show();
    }

    @FXML
    public void jifen() {
        List<gameMenuBar.ScoreRecord> records = loadHistoryScores();

        // 2. 按日期倒序排序
        records.sort((a, b) -> b.date.compareTo(a.date));

        // 3. 构建显示内容
        StringBuilder content = new StringBuilder();
        content.append("历史游戏积分记录\n\n");

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        for (gameMenuBar.ScoreRecord record : records) {
            content.append(sdf.format(record.date))
                    .append("  得分: ")
                    .append(record.score)
                    .append("\n");
        }

        // 4. 显示对话框
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle("积分记录");
        alert.setHeaderText(null);
        alert.setContentText(content.toString());

        // 设置窗口图标（可选）
        Stage stage = (Stage) alert.getDialogPane().getScene().getWindow();
        stage.getIcons().add(icon);

        alert.showAndWait();
    }

    @FXML
    public void buy() {
        try {
            // 加载购买页面的FXML文件
            FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/shop/Shop.fxml"));
            Parent root = loader.load();

            // 获取购买页面的控制器实例
            ShopController shopController = loader.getController();

            // 创建新的Stage并设置Scene
            Stage stage = new Stage();
            stage.setTitle("购买页面");
            stage.setScene(new Scene(root));
            // 如果需要模态展示，可添加以下代码
            stage.initModality(Modality.APPLICATION_MODAL);

            // 展示购买页面
            stage.show();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @FXML
    public void back() {
        if (stage != null) {
            stage.close(); // 关闭当前窗口
        }
    }


    private static class ScoreRecord implements Serializable {
        private static final long serialVersionUID = 1L;
        final long score;
        final Date date;

        ScoreRecord(long score, Date date) {
            this.score = score;
            this.date = date;
        }
    }

    // 加载历史记录（复用gameMenuBar的方法）
    private List<gameMenuBar.ScoreRecord> loadHistoryScores() {
        File file = new File("2048_scores.dat");
        if (!file.exists()) return new ArrayList<>();

        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))) {
            return (List<gameMenuBar.ScoreRecord>) ois.readObject();
        } catch (Exception e) {
            System.err.println("加载历史记录失败: " + e.getMessage());
            return new ArrayList<>();
        }
    }
}